from django.shortcuts import redirect, render, render_to_response, get_object_or_404
from apps.shiyanshi.model import User, LaboratoryMember, Question, QuestionAnswer, AnswerReply
from django.core.paginator import Paginator
from .model import PublishBlog, Groups
from django.http import Http404, HttpResponse, JsonResponse
import hashlib

from apps.shiyanshi.flash import flash, login_required


def md5(string):
    if string:
        return hashlib.md5(string).hexdigest()
    else:
        return None


def home(request):  # 主页

    return render(request, 'home.html')


def inner_home(request):
    user_id = request.session.get('user_id', default=None)
    if user_id:
        user_obj = User.objects.filter(id=user_id)
        return render(request, 'inner_index.html', user_obj)
    return render(request,'inner_index.html')

def login(request):
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user_obj = User.objects.filter(username=username)
        if not user_obj:
            flash(request, 'error', '用户名不存在！')
        if user_obj.password != md5(password):
            flash(request, 'error', '密码错误！')
        else:
            request.session['user_id'] = user_obj.id
        return redirect('inner_home')


def logout(request):
    try:
        del request.session['user_id']
    except KeyError:
        pass
    flash(request, 'success', '注销成功')
    return redirect('home')


def sign_in(request):
    if request.method == 'GET':
        return render(request, 'sign_in.html')
    elif request.method == 'POST':
        school_number = request.POST['school_number']
        truename = request.POST['truename']
        password = request.POST['password']
        repassword = request.POST['repassword']
        qq_number = request.POST['qq_number']
        name = request.POST['name']
        if school_number and truename and password and repassword and qq_number and name:
            if password != repassword:
                flash(request, 'error', '密码与重复密码不一致')
            else:
                member_obj = LaboratoryMember.objects.filter(school_number)
                if not member_obj:
                    flash(request, 'error', '学号不存在！请联系管理员')
                else:
                    if member_obj.flag == 0:
                        if member_obj.truename == truename:
                            user_obj = User(username=school_number,
                                            true_name=truename,
                                            name=name,
                                            password=md5(password))
                            try:
                                user_obj.save()
                            except:
                                flash(request, 'error', '数据库错误请重试！')
                            flash(request, 'success', '注册成功!即将跳转到主页')
                            return redirect('inner_home')
                        else:
                            flash(request, 'error', '学号姓名不匹配')
                    else:
                        flash(request, 'error', '此学号已被注册')
        else:
            flash(request, 'error', '请输入完整表单')


def question_list(request):
    context_list = Question.objects.all().order_by('-time')
    group_obj = Groups.objects.all()
    paginator = Paginator(context_list, 5)
    page = request.GET.get('page')
    contexts = paginator.get_page(page)
    return render(request, 'question_list.html', {'contexts': contexts, 'groups': group_obj})


def question_page(request, question_id):
    quesion_obj = get_object_or_404(Question, id=question_id)
    answer_obj = QuestionAnswer.objects.filter(question_id=question_id)
    answer_reply = {}
    if not answer_obj:
        for answer in answer_obj:
            reply_obj = AnswerReply.objects.filter(answer_id=answer.id)
            answer_reply[answer.id] = reply_obj
    context = {
        'question_obj': quesion_obj,
        'answer_obj': answer_obj,
        'answer_reply': answer_reply,
    }
    return render(request, 'question_page.html', context)


@login_required
def question_creat(request):
    user_id = request.session.get('user_id', deafult=None)
    if request.method == 'GET':
        return render(request, 'question_creat.html')
    elif request.method == 'POST':
        title = request.POST['title']
        content = request.POST['content']
        question_obj = Question(title=title,
                                content=content,
                                author=user_id)
        try:
            question_obj.save()
        except:
            flash(request, 'error', '数据库错误!请重试')


def question_serch(request):
    group_id = request.GET.get('group_id')
    group_obj = get_object_or_404(Groups, id=group_id)
    question_obj = Question.objects.filter(group_id=group_id)


def blog_list(request):
    blogs_all_list = PublishBlog.objects.all()
    paginator = Paginator(blogs_all_list, 2)
    page_num = request.GET.get('page', 1)
    page_of_blogs = paginator.get_page(page_num)
    currentr_page_num = page_of_blogs.number
    page_range = list(range(max(currentr_page_num - 2, 1), currentr_page_num)) + \
                 list(range(currentr_page_num, min(currentr_page_num + 2, paginator.num_pages) + 1))
    if page_range[0] - 1 >= 2:
        page_range.insert(0, '...')
    if paginator.num_pages - page_range[-1] >= 2:
        page_range.append('...')

    if page_range[0] != 1:
        page_range.insert(0, 1)
    if page_range[-1] != paginator.num_pages:
        page_range.append(paginator.num_pages)

    context = {}
    context['page_of_blogs'] = page_of_blogs
    context['blogs'] = page_of_blogs.object_list
    context['group'] = Groups.objects.all()
    context['blogs_count'] = PublishBlog.objects.all().count()
    context['page_range'] = page_range
    return render_to_response('publicBlog.html', context)


def blog_detail(request, blog_pk):
    blog = get_object_or_404(PublishBlog, pk=blog_pk)
    context = {}
    context['blog'] = blog
    context['previous_blog'] = PublishBlog.objects.filter(time__gt=blog.time).last()
    context['next_blog'] = PublishBlog.objects.filter(time__lt=blog.time).first()
    print(PublishBlog.objects.filter(time__lt=blog.time))
    return render_to_response('blog.html', context)
